<script setup>
import {Delete, Download, Edit, Plus, Search, Upload, User} from "@element-plus/icons-vue";
import {reactive, ref,onMounted} from "vue";
import {deleteUser, getUser, insertUser, listUser, updateUser} from "@/api/system/user";
import {ElMessage, ElMessageBox} from "element-plus";
import {validEmail} from "@/utils/validUtil";

// 弹出框标题
const dialogTitle = ref('')

const userList = ref([])

const loading = ref(false)
//总条数
const total = ref(0)
const pages= ref('1')

const queryParams = reactive({
  pageSize: 10,//显示条数
  currentPage: 1,//当前页面
  username: undefined,
  status: undefined
})

const userFrom = reactive({
  id: undefined,
  nickname: '',
  username: undefined,
  password: undefined,
  email: '',
  amount: 0.00,
  roles: undefined,
  remark:'',
})

const clearFrom = () =>{
  userFrom.id = undefined
  userFrom.nickname= ''
  userFrom.username= undefined
  userFrom.password= undefined
  userFrom.email = ''
  userFrom.roles = undefined
  userFrom.remark= ''
}

const openDialog =ref(false)
const roleValue =ref('')

onMounted(()=>{
  getList(queryParams)
})

const getList=(params) =>{
  loading.value = true;
  listUser(params).then(res => {
        const data=res.data;
        userList.value = data.records;
        total.value = data.total;
        queryParams.pageSize = data.size;
        queryParams.currentPage = data.current
        pages.value = data.pages
        loading.value = false;
      }
  );
}

const addUser=() =>{
  clearFrom();
  dialogTitle.value = '添加用户'
  userFrom.username= ''
  userFrom.password= ''
  openDialog.value = true;
}

const updateUserInfo = (row) =>{
  //设置弹出框标题
  clearFrom();
  dialogTitle.value = '修改用户'
  const id=row.id;
  getUser(id).then((res)=>{
    // 将后端返回的数据映射到 userFrom
    const userData = res.data;
    userFrom.roles = res.roles || []; // 注意：roles 字段可能是 List<Role> 类型，需要转换为 Array 格式
    userFrom.id = userData.id; // 注意：id 字段可能是 Long 类型，需要转换为 String 格式
    userFrom.nickname = userData.nickname || '';
    userFrom.amount = userData.amount || 0;
    userFrom.email = userData.email || '';
    userFrom.remark = userData.remark || '';
    openDialog.value = true;
  })

}

const handleClick =(formEl,row)=>{
  if (!formEl) return
  formEl.validate((valid) => {
    if (userFrom.id){
      updateUser(userFrom).then((res) =>{
        ElMessage.success(res.message)
        getList(queryParams)
        openDialog.value = false
      }).catch(()=>{
      })
    }else {
      //添加用户操作
      dialogTitle.value = '添加用户'
      insertUser(userFrom).then((res)=>{
        ElMessage.success(res.message)
        openDialog.value = false
        getList(queryParams)
      }).catch(()=>{
      })
    }
  })
}
let ids = []
const handleSelectionChange=(selection)=> {
  ids = selection.map(item => item.id);
}
const handleDelete=(row)=>{
  const userIds=row.id || ids
  ElMessageBox.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
    return deleteUser(userIds);
  }).then(() => {
    getList(queryParams)
    ElMessage.success("删除成功");
  }).catch(() => {});
}


const onSubmit = () => {
  console.log(queryParams)
}
const ruleFormRef = ref(null)
/**
 * 账号校验
 * @param rule
 * @param value
 * @param callback
 */
const validateUsername = (rule, value, callback) => {
  value=value.trim()
  const regexp=/^[a-zA-Z0-9]{5,11}$/
  if (value === '') {
    callback(new Error('请输入账号'))
  } else if (!regexp.test(value)){
    callback(new Error('用户名必须为5-11位字母、数字组成'))
  }else{
    callback()
  }
}
/**
 * 密码校验
 * @param rule
 * @param value
 * @param callback
 */
const validatePassword = (rule, value, callback) => {
  value = value.trim()
  const regexp=/^[a-zA-Z0-9.@#]{6,20}$/
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!regexp.test(value)) {
    callback(new Error('密码长度为6-20位字母、数字、符号(.@#)'))
  }else {
    callback()
  }
}
/**
 * 校验邮箱
 * @param rule
 * @param value
 * @param callback
 */
const validateEmail = (rule, value, callback) => {
  value = value.trim();
  // 校验是否为空
  if (value === '') {
    callback(new Error('请输入邮箱')); // 错误情况，返回错误信息
  }
  // 校验是否格式不正确
  else if (!validEmail(value)) {
    callback(new Error('邮箱格式不符')); // 错误情况，返回错误信息
  }
  else {
    callback(); // 这里 callback 不带参数表示校验通过
  }
};
const validateNickname = (rule, value, callback) => {
  value = value.trim();
  const regexp=/^[a-zA-Z0-9.@#]{0,30}$/
  if (!regexp.test(value)) {
    callback(new Error('昵称长度为0-30位字符'))
  }else {
    callback()
  }
};
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
  nickname: [{ validator: validateNickname, trigger: 'submit' }],
})

const handleSizeChange = (pageSize) => {
  queryParams.pageSize = pageSize;
  getList(queryParams)
}
const handleCurrentChange = (currentPage) => {
  queryParams.currentPage = currentPage;
  getList(queryParams)
}
</script>

<template>
  <div class="box">
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="用户名">
        <el-input style="width: 150px" v-model="queryParams.username" placeholder="用户名" clearable/>
      </el-form-item>
      <el-form-item label="选择状态">
        <el-select
            style="width: 120px"
            v-model="queryParams.status"
            placeholder="选择状态"
            clearable>
          <el-option label="正常" value="0"/>
          <el-option label="停用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker
            style="width: 200px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :icon="Search">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            :icon="Plus"
            @click="addUser"
            size="small">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            @click="handleDelete"
            :icon="Delete"
            size="small">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            :icon="Upload"
            size="small">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            :icon="Download"
            size="small">导出
        </el-button>
      </el-col>

    </el-row>

    <el-table @selection-change="handleSelectionChange" size="large" v-loading="loading" stripe max-height="100%" :data="userList" style="width: 100%;">
      <el-table-column type="selection" width="40" align="center"/>
      <el-table-column prop="id" align="center" label="编号" width="60"/>
      <el-table-column prop="username" label="用户名" align="center" min-width="180" />
      <el-table-column prop="nickname" label="用户昵称" align="center" min-width="180"/>
      <el-table-column prop="email" label="邮箱" class-name="ellipsis" align="center" min-width="180"/>
      <el-table-column label="状态" align="center" width="80">
        <template #default="scope">
          <el-tag style="user-select: none" :type=" scope.row.status === '0' ? 'success' : 'danger' ">
            {{ scope.row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="余额" class-name="ellipsis" align="center" min-width="120"/>
      <el-table-column prop="createTime" label="创建时间" align="center" min-width="180"/>
      <el-table-column #default="scope" fixed="right" label="操作" align="center" width="150">
        <template v-if="scope.row.id !== 1">
          <el-button
              size="small"
              link
              type="primary"
              @click="updateUserInfo(scope.row)"
              :icon="Edit">修改
          </el-button>
          <el-button
              size="small"
              link
              type="danger"
              @click="handleDelete(scope.row)"
              :icon="Delete">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="page">
      <el-pagination
          size="small"
          v-model:current-page="queryParams.currentPage"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10,30, 50, 100]"
          :size="pages"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog class="dialog-from" v-model="openDialog" :title="dialogTitle" width="300" center>
      <el-form :rules="rules" ref="ruleFormRef" size="default" :model="userFrom">
        <el-form-item  v-if="userFrom.username !== undefined" prop="username" label="账号">
          <el-input v-model="userFrom.username" maxlength="11" minlength="5"/>
        </el-form-item>
        <el-form-item v-if="userFrom.password !== undefined" prop="password" label="密码">
          <el-input v-model="userFrom.password" type="password" minlength="6" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="userFrom.amount" type="number" maxlength="9"/>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userFrom.nickname" maxlength="30"/>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="userFrom.email" />
        </el-form-item>
        <el-form-item v-show="userFrom.roles" label="角色">
          <el-select
              v-model="roleValue"
              placeholder="选择角色">
            <el-option
                v-for="role in userFrom.roles"
                :key="role.roleKey"
                :label="role.roleName"
                :value="role.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="userFrom.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 100px" @click="openDialog = false">取消</el-button>
          <el-button style="width: 100px" type="primary" @click="handleClick(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style >
.el-input__wrapper{
  width: 100px !important;
}

.box {
  display: flex;
  flex: 1; /* 占满父容器的剩余空间 */
  overflow: hidden; /* 避免父容器出现滚动条 */
  flex-direction: column;
}
.cell .el-button{
  margin-left: 0;
}

.ellipsis .cell {
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号显示超出部分 */
  max-width: 150px;
}
.el-form {
  width: 100%;
  display: flex;
  align-items: start;
  flex-flow: wrap;
  justify-content: left;
}
.el-table {
  min-height: 300px; /* 表格高度随容器调整 */
  overflow-y: auto; /* 表格超出部分滚动 */
}
.el-scrollbar__wrap--hidden-default{
  max-height: 100% !important;
}
.dialog-from .el-row{
  justify-content: space-around;
}

.mb8 {
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
}

.mb8 .el-col {
  margin-top: 5px;
}
.page{
  width: 100%;
  height: auto;
  display: flex;
  margin-top: 20px;
  justify-content: flex-end;
}
.dialog-from .el-form-item{
  width: 100%;
}
</style>
